const http = require('http');
const fs = require('fs');
const url = require('url');
const cors = require('cors');

const server = http.createServer((req, res) => {
    // 设置 CORS 头
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63342');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    if (req.method === 'OPTIONS') {
        // 处理预检请求
        res.writeHead(204);
        res.end();
        return;
    }

    if (req.method === 'POST' && req.url === '/save-bounds') {
        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            try {
                const bounds = JSON.parse(body);
                const jsonString = JSON.stringify(bounds, null, 2);
                fs.writeFile('./bounds_json/bounds.json', jsonString, 'utf8', (err) => {
                    if (err) {
                        console.error('写入文件时出错:', err);
                        res.writeHead(500, { 'Content-Type': 'text/plain' });
                        res.end('Internal Server Error');
                        return;
                    }
                    console.log('bounds.json 文件已成功保存');
                    res.writeHead(200, { 'Content-Type': 'text/plain' });
                    res.end('File saved successfully');
                });
            } catch (error) {
                console.error('解析 JSON 时出错:', error);
                res.writeHead(400, { 'Content-Type': 'text/plain' });
                res.end('Bad Request');
            }
        });
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
    }
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});
